#include <string>
#include <iostream>
#include <queue>
#include <pthread.h>

template<typename T>
class BlockQueue
{
public:
    BlockQueue(int cap)
    :_cap(cap)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_consumer, nullptr);
        pthread_cond_init(&_productor, nullptr);
    }

    bool IsFull()
    {
        return _bq.size() == _cap;
    }   

    bool IsEmpty()
    {
        return _bq.empty();
    }

    void Excute(T& in)
    {
        pthread_mutex_lock(&_mutex);
        if (IsFull())
        {
            pthread_cond_wait(&_productor, &_mutex);
        }
        std::cout << in << std::endl;
        _bq.push(in);
        pthread_cond_signal(&_consumer);
        pthread_mutex_unlock(&_mutex);
    }

    void Pop(T* out)
    {
        pthread_mutex_lock(&_mutex);
        if (IsEmpty())
        {
            pthread_cond_wait(&_consumer, &_mutex);
        }
        *out = _bq.front(); 
        _bq.pop();
        pthread_cond_signal(&_productor);
        pthread_mutex_unlock(&_mutex);
    }

    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_consumer);
        pthread_cond_destroy(&_productor);
    }

private:
    std::queue<T> _bq;
    int _cap;
    pthread_mutex_t _mutex;
    pthread_cond_t _consumer;
    pthread_cond_t _productor;
};